import socket
import socketserver
from biaoge import *
from PyQt5.QtGui import QPixmap

Path=""

ip_port=("192.168.43.55",19984)

# def get_host_ip():
#     """
#     查询本机ip地址
#     :return:
#     """
#     try:
#         s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#         s.connect(('8.8.8.8',80))
#         ip=s.getsockname()[0]
#     finally:
#         s.close()
#
#     return ip

class MyServer(socketserver.BaseRequestHandler):

    def TCP_Insert(self,time,number):
        conn = pymysql.connect(host='localhost', port=3306, user='root', password="root", db="tab")
        cur = conn.cursor()

        id1 = number
        name1 = time
        sql1 = "INSERT INTO tab (车牌号,时间) VALUES ('" + id1 + "','" + name1 + "')"
       #sql1 = "INSERT INTO tab  (id,NAME) VALUES ("+id1+",'"+name1+"')"
        # 打印测试
        print(sql1)
        # print(sql2)
        # 执行sql语句，并发送给数据库
        cur.execute(sql1)
        # cur.execute(sql2)
        conn.commit()  # 事务提交数据库
        cur.close()
        conn.close()

    def handle(self):
        print("conn is :",self.request) # conn
        print("addr is :",self.client_address) # addr
        
        while True:
            try:
                self.str = self.request.recv(9)
                data = bytearray(self.str)
                '''
                find() 方法检测字符串中是否包含子字符串 str ，
                如果指定 beg（开始） 和 end（结束） 范围，则检查是否包含在指定范围内，
                如果指定范围内如果包含指定索引值，返回的是索引值在字符串中的起始位置。
                如果不包含索引值，返回-1。
                '''
                headIndex = data.find(b'\xff\xaa\xff\xaa')
                print(headIndex)
                
                if headIndex == 0:
                    H=headIndex+4
                    T=headIndex+5
                    allLen = int.from_bytes(data[H:T], byteorder='little')
                    tlen=allLen
                    print("时间数据长度 ", tlen)

                    H=T
                    T=T+4
                    allLen = int.from_bytes(data[H:T], byteorder='little')
                    print("数据总长度为", allLen)


 
                    curSize = 0
                    allData = b''
                    while curSize < allLen:
                        data = self.request.recv(1024)
                        allData += data
                        curSize += len(data)
 
                    print("recv data len is ", len(allData))
                    #接收到的数据，前64字节是guid，后面的是图片数据
                    arrGuid = allData[0:64]
                    #去除guid末尾的0
                    tail = arrGuid.find(b'\x00')
                    arrGuid = arrGuid[0:tail]
                    strGuid = str(int.from_bytes(arrGuid, byteorder = 'little')) #for test
                    
                    print("-------------request guid is ", strGuid)

                    time1 = allData[64:64+tlen]
                    print(time1)
                    strtime = time1.decode('utf-8')
                    print("时间是", strtime)
                    self.TCP_Insert(strtime, '66')


                    imgData = allData[64+tlen:]
                    strImgFile = "2.jpg"
                    print("img file name is ", strImgFile)
                    Path="E:"+"\\"+strImgFile
                    #将图片数据保存到本地文件
                    with open(Path, 'wb') as f:
                        f.write(imgData)
                        f.close()


                    print(Path)



                    break
            except Exception as e:
                print(e)
                break
 
 
# if __name__ == "__main__":
#     s = socketserver.ThreadingTCPServer(ip_port, MyServer)
#     print("start listen")
#     s.serve_forever()

def MyServer_start():
    s = socketserver.ThreadingTCPServer(ip_port, MyServer)
    print("start listen")

    s.serve_forever()
